﻿using System;
using System.Activities.Persistence;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace YasharEl.Infrastructure.WorkflowModel.Persistence.Extensions
{
    public class GenericValuePromotionPersistenceExtension : PersistenceParticipant
    {
        #region Static Fields

        public static XNamespace PromotedPropertyXNamespace =
            XNamespace.Get("http://YasharEl.Infrastructure.Workflow/2013/Persistence");

        #endregion

        #region Fields

        private IDictionary<XName, object> promotedProperties;

        #endregion

        #region Properties

        public IDictionary<XName, object> PromotedProperties
        {
            get
            {
                return promotedProperties;
            }
        }

        #endregion

        #region Constructors

        public GenericValuePromotionPersistenceExtension()
        {
            this.promotedProperties = new Dictionary<XName, object>();
        }

        #endregion

        #region Public Methods

        public void AddPromotedVariable(string variableName, object variableValue)
        {
            this.promotedProperties[PromotedPropertyXNamespace.GetName(variableName)] = variableValue;
        }

        public void ClearExistingPromotionData()
        {
            this.promotedProperties.Clear();
        }

        #endregion

        #region PersistenceParticipant Overrides

        protected override void CollectValues(out IDictionary<XName, object> readWriteValues, out IDictionary<XName, object> writeOnlyValues)
        {
            readWriteValues = this.promotedProperties;
            writeOnlyValues = null;
        }

        protected override void PublishValues(IDictionary<XName, object> readWriteValues)
        {
            base.PublishValues(readWriteValues);

            this.promotedProperties = new Dictionary<XName, object>();
            if (readWriteValues != null && readWriteValues.Count > 0)
            {
                foreach (var readWriteValue in readWriteValues)
                {
                    if (readWriteValue.Key.Namespace == PromotedPropertyXNamespace)
                    {
                        this.promotedProperties[readWriteValue.Key] = readWriteValue.Value;
                    }
                }
            }
        }

        #endregion
    }
}
